package com.lty.jeeg.server.modules.fas.service.impl;

import com.google.common.collect.Lists;
import com.lty.jeeg.server.common.page.table.PageTableHandler;
import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;
import com.lty.jeeg.server.common.utils.BeanConverter;
import com.lty.jeeg.server.modules.fas.dao.GoodsCategoryDao;
import com.lty.jeeg.server.modules.fas.dao.GoodsDao;
import com.lty.jeeg.server.modules.fas.dto.GoodsCategoryDTO;
import com.lty.jeeg.server.modules.fas.dto.GoodsDTO;
import com.lty.jeeg.server.modules.fas.export.GoodsExportEntity;
import com.lty.jeeg.server.modules.fas.model.Goods;
import com.lty.jeeg.server.modules.fas.service.GoodsService;
import com.lty.jeeg.server.modules.sys.dao.FileInfoDao;
import com.lty.jeeg.server.modules.sys.model.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : LTY
 * @date : 2019-01-18 16:37:02
 * Description : 商品
 */
@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    private final GoodsDao goodsDao;

    private final GoodsCategoryDao goodsCategoryDao;

    private final FileInfoDao fileInfoDao;

    @Autowired
    public GoodsServiceImpl(GoodsDao goodsDao, GoodsCategoryDao goodsCategoryDao, FileInfoDao fileInfoDao) {
        this.goodsDao = goodsDao;
        this.goodsCategoryDao = goodsCategoryDao;
        this.fileInfoDao = fileInfoDao;
    }

    @Override
    public GoodsDTO getById(Long id) {
        GoodsDTO goodsDTO = goodsDao.getById(id);
        String screenshotPath = goodsDTO.getScreenshotPath();
        if (StringUtils.isNotEmpty(screenshotPath)) {
            List<FileInfo> screenshots = Lists.newArrayList();
            String[] screenshotArray = screenshotPath.substring(1).split("\\|");
            for (String fileId: screenshotArray) {
                screenshots.add(fileInfoDao.getById(fileId));
            }
            goodsDTO.setScreenshotPaths(screenshots);
        }
        return goodsDTO;
    }

    @Override
    public GoodsDTO getByCode(String code) {
        return goodsDao.getByCode(code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        log.debug("删除Goods=>{}", id);
        return goodsDao.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(GoodsDTO goodsDTO) {
        goodsDTO.preUpdate();
        log.debug("修改Goods=>{}", goodsDTO.getId());
        return goodsDao.update(BeanConverter.map(goodsDTO, Goods.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(GoodsDTO goodsDTO) {
        goodsDTO.preInsert();
        Long id = goodsDao.save(BeanConverter.map(goodsDTO, Goods.class));
        log.debug("新增Goods=>{}", id);
        return goodsDTO.getId();
    }

    @Override
    public PageTableResponse list(PageTableRequest request) {
        return new PageTableHandler(
                request1 -> goodsDao.count(request1.getParams()),
                request2 -> goodsDao.list(
                        request2.getParams(), request2.getOffset(), request2.getLimit()))
                .handle(request);
    }

    @Override
    public List<GoodsExportEntity> getExportDatas(GoodsDTO goodsDTO) {
        return goodsDao.getExportDatas(goodsDTO);
    }

    /**
     * 导入商品以及校验导入数据
     *
     * @param goodList
     * @return 导入失败List
     * @author xuchen
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GoodsExportEntity> importData(List<Object> goodList) {
        List<GoodsExportEntity> failList = new ArrayList<>();   //导入失败List
        //处理数据
        if (goodList != null && goodList.size() > 0) {
            for (Object obj : goodList) {
                if (obj != null) {
                    StringBuilder sb = new StringBuilder();//错误提示
                    GoodsExportEntity goodsExportEntity = (GoodsExportEntity) obj;
                    boolean flag = true;
                    String unitPrice = goodsExportEntity.getUnitPriceExport();
                    Goods goods = BeanConverter.map(goodsExportEntity, Goods.class);
                    //数量
                    if (!StringUtils.isEmpty(unitPrice)) {
                        try {
                            goods.setUnitPrice(new BigDecimal(Double.valueOf(unitPrice)));
                        } catch (Exception e) {
                            flag = false;
                            sb.append("单价只能填写整数或小数;");
                        }
                    }

                    //校验数据并初始化值 TODO
                    String code = goodsExportEntity.getCode();  //商品编码
                    String name = goodsExportEntity.getName();  //商品名称
                    String categoryName = goodsExportEntity.getCategoryName();  //商品分类名称
                    String isCommonName = goodsExportEntity.getIsCommonName();  //是否常规物料
                    String isConsumablesName = goodsExportEntity.getIsConsumablesName();    //是否耗材
                    String remark = goodsExportEntity.getRemark();    //是否耗材
                    if (StringUtils.isEmpty(remark)) {
                        goodsExportEntity.setRemark("");
                    }
                    //编码
                    if (StringUtils.isNotEmpty(code)) {
                        //去重校验
                        GoodsDTO goodsDTO = goodsDao.getByCode(code);
                        if (goodsDTO != null) {
                            flag = false;
                            sb.append("商品编码不能重复,请核对;");
                        }
                    } else {
                        flag = false;
                        sb.append("商品编码不能为空;");
                    }
                    //名称
                    if (StringUtils.isEmpty(name)) {
                        flag = false;
                        sb.append("商品名称不能为空;");
                    }
                    //商品分类
                    if (StringUtils.isNotEmpty(categoryName)) {
                        //根据商品分类名称查询分类对象
                        try {
                            GoodsCategoryDTO categoryDTO = goodsCategoryDao.getByName(categoryName);
                            if (categoryDTO != null && categoryDTO.getId() != null) {
                                //设置商品分类id
                                goods.setCategory(categoryDTO.getId());
                            } else {
                                flag = false;
                                sb.append("该商品分类不存在;");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            flag = false;
                        }
                    } else {
                        flag = false;
                        sb.append("商品分类不能为空;");
                    }

                    //是否常规物料
                    if (StringUtils.isNotEmpty(isCommonName)) {
                        if ("是".equals(isCommonName)) {
                            goods.setIsCommon(1);
                        } else if ("否".equals(isCommonName)) {
                            goods.setIsCommon(0);
                        } else {
                            flag = false;
                            sb.append("是否常规物料填写不规范(只能填是/否);");
                        }
                    } else {
                        flag = false;
                        sb.append("是否常规物料不能为空;");
                    }

                    //是否耗材
                    if (StringUtils.isNotEmpty(isConsumablesName)) {
                        if ("是".equals(isConsumablesName)) {
                            goods.setIsConsumables(1);
                        } else if ("否".equals(isConsumablesName)) {
                            goods.setIsConsumables(0);
                        } else {
                            flag = false;
                            sb.append("是否耗材填写不规范(只能填是/否);");
                        }
                    } else {
                        flag = false;
                        sb.append("是否耗材不能为空;");
                    }

                    if (flag) {
                        //导入成功
                        Long id = goodsDao.save(goods);
                        log.debug("导入Goods=>{}", id);
                    } else {
                        //导入失败
                        goodsExportEntity.setFailMsg(sb.toString());
                        failList.add(goodsExportEntity);
                    }
                }
            }
        }
        return failList;
    }
}
